Telegram Group & Telegram Channel
🔓Что выведет следующий код?


#include <iostream>
using namespace std;

class Base {
public:
Base() {
cout << "Base constructor: ";
call();
}
virtual void call() { cout << "Base::call\n"; }
};

class Derived : public Base {
int x = init();

int init() {
cout << "Derived::init\n";
return 42;
}

public:
Derived() {
cout << "Derived constructor\n";
}

void call() override {
cout << "Derived::call, x = " << x << "\n";
}
};

int main() {
Derived d;
return 0;
}


🔢Варианты ответа:

A)

Derived::init
Derived constructor


B)

Derived::init
Derived constructor


C)

Base constructor: Derived::call, x = 42
Derived constructor


D)

Derived::call, x = <undefined>
Derived::init
Derived constructor


Правильный ответ: B

💡Почему?
В момент вызова конструктора Base, объект ещё не стал Derived. Виртуальная функция вызывается в контексте Base.



tg-me.com/cpluspluc/1034
Create:
Last Update:

🔓Что выведет следующий код?


#include <iostream>
using namespace std;

class Base {
public:
Base() {
cout << "Base constructor: ";
call();
}
virtual void call() { cout << "Base::call\n"; }
};

class Derived : public Base {
int x = init();

int init() {
cout << "Derived::init\n";
return 42;
}

public:
Derived() {
cout << "Derived constructor\n";
}

void call() override {
cout << "Derived::call, x = " << x << "\n";
}
};

int main() {
Derived d;
return 0;
}


🔢Варианты ответа:

A)

Derived::init
Derived constructor


B)

Derived::init
Derived constructor


C)

Base constructor: Derived::call, x = 42
Derived constructor


D)

Derived::call, x = <undefined>
Derived::init
Derived constructor


Правильный ответ: B

💡Почему?
В момент вызова конструктора Base, объект ещё не стал Derived. Виртуальная функция вызывается в контексте Base.

BY C++ Academy


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/cpluspluc/1034

View MORE
Open in Telegram


C Academy Telegram | DID YOU KNOW?

Date: |

The Singapore stock market has alternated between positive and negative finishes through the last five trading days since the end of the two-day winning streak in which it had added more than a dozen points or 0.4 percent. The Straits Times Index now sits just above the 3,060-point plateau and it's likely to see a narrow trading range on Monday.

The seemingly negative pandemic effects and resource/product shortages are encouraging and allowing organizations to innovate and change.The news of cash-rich organizations getting ready for the post-Covid growth economy is a sign of more than capital spending plans. Cash provides a cushion for risk-taking and a tool for growth.

C Academy from in


Telegram C++ Academy
FROM USA